package com.xy.webadmin.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xy.webadmin.app.service.*;
import com.xy.webadmin.app.dao.*;
import com.xy.webadmin.app.model.*;
import com.xy.webadmin.upms.service.SysDeptService;
import com.xy.common.core.base.dao.BaseDaoMapper;
import com.xy.common.core.constant.GlobalDeletedFlag;
import com.xy.common.core.object.TokenData;
import com.xy.common.core.object.MyRelationParam;
import com.xy.common.core.object.CallResult;
import com.xy.common.core.base.service.BaseService;
import com.xy.common.core.util.MyModelUtil;
import com.xy.common.sequence.wrapper.IdGeneratorWrapper;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 班级数据操作服务类。
 *
 * @author xiaoyue
 * @date 2025-05-13
 */
@Slf4j
@Service("clazzService")
public class ClazzServiceImpl extends BaseService<Clazz, Long> implements ClazzService {

    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentClazzMapper studentClazzMapper;
    @Autowired
    private TeacherClazzMapper teacherClazzMapper;
    @Autowired
    private ClazzService clazzService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private StudentClazzService studentClazzService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherClazzService teacherClazzService;
    @Autowired
    private TeacherService teacherService;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<Clazz> mapper() {
        return clazzMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Clazz saveNew(Clazz clazz) {
        clazzMapper.insert(this.buildDefaultValue(clazz));
        return clazz;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<Clazz> clazzList) {
        if (CollUtil.isNotEmpty(clazzList)) {
            clazzList.forEach(this::buildDefaultValue);
            clazzMapper.insertList(clazzList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(Clazz clazz, Clazz originalClazz) {
        clazz.setCreateUserId(originalClazz.getCreateUserId());
        clazz.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        clazz.setCreateTime(originalClazz.getCreateTime());
        clazz.setUpdateTime(new Date());
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<Clazz> uw = this.createUpdateQueryForNullValue(clazz, clazz.getId());
        return clazzMapper.update(clazz, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        if (clazzMapper.deleteById(id) == 0) {
            return false;
        }
        // 开始删除多对多子表的关联
        StudentClazz studentClazz = new StudentClazz();
        studentClazz.setClazzId(id);
        studentClazzMapper.delete(new QueryWrapper<>(studentClazz));
        TeacherClazz teacherClazz = new TeacherClazz();
        teacherClazz.setClazzId(id);
        teacherClazzMapper.delete(new QueryWrapper<>(teacherClazz));
        // 开始删除多对多父表的关联
        return true;
    }

    @Override
    public List<Clazz> getClazzList(Clazz filter, String orderBy) {
        return clazzMapper.getClazzList(filter, orderBy);
    }

    @Override
    public List<Clazz> getClazzListWithRelation(Clazz filter, String orderBy) {
        List<Clazz> resultList = clazzMapper.getClazzList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Override
    public boolean hasChildren(Long id) {
        Clazz filter = new Clazz();
        filter.setParentId(id);
        return getCountByFilter(filter) > 0;
    }

    @Override
    public List<Clazz> getNotInClazzListByStudentId(Long studentId, Clazz filter, String orderBy) {
        List<Clazz> resultList;
        if (studentId != null) {
            resultList = clazzMapper.getNotInClazzListByStudentId(studentId, filter, orderBy);
        } else {
            resultList = getClazzList(filter, orderBy);
        }
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        return resultList;
    }

    @Override
    public List<Clazz> getClazzListByStudentId(
            Long studentId, Clazz filter, StudentClazz studentClazzFilter, String orderBy) {
        List<Clazz> resultList =
                clazzMapper.getClazzListByStudentId(studentId, filter, studentClazzFilter, orderBy);
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        this.buildRelationForStudentClazzList(resultList);
        return resultList;
    }

    @Override
    public Map<Long, List<Clazz>> getClazzListMapByStudentList(
            List<Student> studentList, Clazz filter, String orderBy) {
        List<Long> studentIds = studentList.stream().map(Student::getId).collect(Collectors.toList());
        List<Clazz> resultList =
                clazzMapper.getClazzListByStudentIds(studentIds, filter, orderBy);
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        this.buildRelationForStudentClazzList(resultList);
        return resultList.stream().collect(Collectors.groupingBy(s -> s.getStudentClazz().getStudentId()));
    }

    @Override
    public List<Clazz> getNotInClazzListByTeacherId(Long teacherId, Clazz filter, String orderBy) {
        List<Clazz> resultList;
        if (teacherId != null) {
            resultList = clazzMapper.getNotInClazzListByTeacherId(teacherId, filter, orderBy);
        } else {
            resultList = getClazzList(filter, orderBy);
        }
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        return resultList;
    }

    @Override
    public List<Clazz> getClazzListByTeacherId(
            Long teacherId, Clazz filter, TeacherClazz teacherClazzFilter, String orderBy) {
        List<Clazz> resultList =
                clazzMapper.getClazzListByTeacherId(teacherId, filter, teacherClazzFilter, orderBy);
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        this.buildRelationForTeacherClazzList(resultList);
        return resultList;
    }

    @Override
    public Map<Long, List<Clazz>> getClazzListMapByTeacherList(
            List<Teacher> teacherList, Clazz filter, String orderBy) {
        List<Long> teacherIds = teacherList.stream().map(Teacher::getId).collect(Collectors.toList());
        List<Clazz> resultList =
                clazzMapper.getClazzListByTeacherIds(teacherIds, filter, orderBy);
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        this.buildRelationForTeacherClazzList(resultList);
        return resultList.stream().collect(Collectors.groupingBy(s -> s.getTeacherClazz().getTeacherId()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addStudentClazzList(List<StudentClazz> studentClazzList, Long clazzId) {
        TokenData tokenData = TokenData.takeFromRequest();
        for (StudentClazz studentClazz : studentClazzList) {
            studentClazz.setId(idGenerator.nextLongId());
            studentClazz.setClazzId(clazzId);
            studentClazz.setCreateTime(new Date());
            studentClazz.setUpdateTime(new Date());
            studentClazz.setCreateUserId(tokenData.getUserId());
            studentClazz.setUpdateUserId(tokenData.getUserId());
            studentClazzMapper.insert(studentClazz);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateStudentClazz(StudentClazz studentClazz) {
        StudentClazz filter = new StudentClazz();
        filter.setClazzId(studentClazz.getClazzId());
        filter.setStudentId(studentClazz.getStudentId());
        StudentClazz originalOne = studentClazzMapper.selectOne(new QueryWrapper<>(filter));
        studentClazz.setCreateTime(originalOne.getCreateTime());
        studentClazz.setUpdateTime(new Date());
        studentClazz.setCreateUserId(originalOne.getCreateUserId());
        studentClazz.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        UpdateWrapper<StudentClazz> uw =
                BaseService.createUpdateQueryForNullValue(studentClazz, StudentClazz.class);
        uw.setEntity(filter);
        return studentClazzMapper.update(studentClazz, uw) > 0;
    }

    @Override
    public StudentClazz getStudentClazz(Long clazzId, Long studentId) {
        StudentClazz filter = new StudentClazz();
        filter.setClazzId(clazzId);
        filter.setStudentId(studentId);
        return studentClazzMapper.selectOne(new QueryWrapper<>(filter));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeStudentClazz(Long clazzId, Long studentId) {
        StudentClazz filter = new StudentClazz();
        filter.setClazzId(clazzId);
        filter.setStudentId(studentId);
        return studentClazzMapper.delete(new QueryWrapper<>(filter)) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeStudentClazzList(Long clazzId, List<Long> studentIdList) {
        LambdaQueryWrapper<StudentClazz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentClazz::getClazzId, clazzId);
        queryWrapper.in(StudentClazz::getStudentId, studentIdList);
        studentClazzMapper.delete(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addTeacherClazzList(List<TeacherClazz> teacherClazzList, Long clazzId) {
        TokenData tokenData = TokenData.takeFromRequest();
        for (TeacherClazz teacherClazz : teacherClazzList) {
            teacherClazz.setId(idGenerator.nextLongId());
            teacherClazz.setClazzId(clazzId);
            teacherClazz.setCreateTime(new Date());
            teacherClazz.setUpdateTime(new Date());
            teacherClazz.setCreateUserId(tokenData.getUserId());
            teacherClazz.setUpdateUserId(tokenData.getUserId());
            teacherClazzMapper.insert(teacherClazz);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateTeacherClazz(TeacherClazz teacherClazz) {
        TeacherClazz filter = new TeacherClazz();
        filter.setClazzId(teacherClazz.getClazzId());
        filter.setTeacherId(teacherClazz.getTeacherId());
        TeacherClazz originalOne = teacherClazzMapper.selectOne(new QueryWrapper<>(filter));
        teacherClazz.setCreateTime(originalOne.getCreateTime());
        teacherClazz.setUpdateTime(new Date());
        teacherClazz.setCreateUserId(originalOne.getCreateUserId());
        teacherClazz.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        UpdateWrapper<TeacherClazz> uw =
                BaseService.createUpdateQueryForNullValue(teacherClazz, TeacherClazz.class);
        uw.setEntity(filter);
        return teacherClazzMapper.update(teacherClazz, uw) > 0;
    }

    @Override
    public TeacherClazz getTeacherClazz(Long clazzId, Long teacherId) {
        TeacherClazz filter = new TeacherClazz();
        filter.setClazzId(clazzId);
        filter.setTeacherId(teacherId);
        return teacherClazzMapper.selectOne(new QueryWrapper<>(filter));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeTeacherClazz(Long clazzId, Long teacherId) {
        TeacherClazz filter = new TeacherClazz();
        filter.setClazzId(clazzId);
        filter.setTeacherId(teacherId);
        return teacherClazzMapper.delete(new QueryWrapper<>(filter)) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeTeacherClazzList(Long clazzId, List<Long> teacherIdList) {
        LambdaQueryWrapper<TeacherClazz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeacherClazz::getClazzId, clazzId);
        queryWrapper.in(TeacherClazz::getTeacherId, teacherIdList);
        teacherClazzMapper.delete(queryWrapper);
    }

    @Override
    public CallResult verifyRelatedData(Clazz clazz, Clazz originalClazz) {
        String errorMessageFormat = "数据验证失败，关联的%s并不存在，请刷新后重试！";
        //这里是基于字典的验证。
        if (this.needToVerify(clazz, originalClazz, Clazz::getParentId)
                && !clazzService.existId(clazz.getParentId())) {
            return CallResult.error(String.format(errorMessageFormat, "父级"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(clazz, originalClazz, Clazz::getCompanyId)
                && !sysDeptService.existId(clazz.getCompanyId())) {
            return CallResult.error(String.format(errorMessageFormat, "公司"));
        }
        return CallResult.ok();
    }

    private void buildRelationForStudentClazzList(List<Clazz> resultList) {
        List<StudentClazz> studentClazzList =
                resultList.stream().map(Clazz::getStudentClazz).collect(Collectors.toList());
        studentClazzService.buildRelationForDataList(studentClazzList, MyRelationParam.dictOnly());
    }

    private void buildRelationForTeacherClazzList(List<Clazz> resultList) {
        List<TeacherClazz> teacherClazzList =
                resultList.stream().map(Clazz::getTeacherClazz).collect(Collectors.toList());
        teacherClazzService.buildRelationForDataList(teacherClazzList, MyRelationParam.dictOnly());
    }

    private Clazz buildDefaultValue(Clazz clazz) {
        if (clazz.getId() == null) {
            clazz.setId(idGenerator.nextLongId());
        }
        TokenData tokenData = TokenData.takeFromRequest();
        clazz.setCreateUserId(tokenData.getUserId());
        clazz.setUpdateUserId(tokenData.getUserId());
        Date now = new Date();
        clazz.setCreateTime(now);
        clazz.setUpdateTime(now);
        clazz.setIsDeleted(GlobalDeletedFlag.NORMAL);
        return clazz;
    }
}
